<?php

namespace API\ORG;

class Xml {

    /**
     * @var \XMLWriter
     */
    private static $writer;

    private static function start() {
        self::$writer = new \XMLWriter();
        self::$writer->openMemory();
        self::$writer->setIndent(true);
        self::$writer->setIndentString('    ');
        self::$writer->startDocument('1.0', 'UTF-8');
    }

    private static function end() {
        if (self::$writer) {
            self::$writer->endDocument();
            return self::$writer->outputMemory();
        }
        return false;
    }

    private static $defaultElement = 'item';

    public static function setDefault($name) {
        self::$defaultElement = $name;
    }

    private static $cDataElements = array();

    public static function setCDATA() {
        self::$cDataElements += func_get_args();
        self::$cDataElements = array_unique(self::$cDataElements);
    }

    private static function buildItem($key, $data) {
        if (is_int($key)) {
            $key = self::$defaultElement;
        }
        self::$writer->startElement($key);
        if (is_object($data)) {
            $data = (array)$data;
        } elseif (is_resource($data)) {
            $data = get_resource_type($data);
        }
        if (is_array($data)) {
            foreach ($data as $k => $v) {
                self::buildItem($k, $v);
            }
        } else {
            if (in_array($key, self::$cDataElements)) {
                self::$writer->writeCdata($data);
            } else {
                self::$writer->writeRaw($data);
            }
        }
        self::$writer->endElement();
    }

    public static function build($data) {
        self::start();
        self::$writer->startElement('response');
        self::$writer->writeAttribute('org', 'HxMvc');
        foreach ($data as $key => $value) {
            self::buildItem($key, $value);
        }
        self::$writer->endElement();
        return self::end();
    }

}